package algdat;

import java.io.File;
import java.io.FileReader;
import java.util.Scanner;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, Nov 5, 2007
 */
public class Ovning31 {

    private static Person readFile() throws Exception {
        Person start = null;
        Person p;
        Person prev = null;
        File file = new File("namn2.dat");
        FileReader fr;
        fr = new FileReader(file);
        Scanner scanner = new Scanner(fr);

        while (scanner.hasNext()) {
            p = new Person();
            p.name = scanner.nextLine();
            p.next = null;
            if (start == null) {
                start = p;
            } else {
                prev.next = p;
            }
            prev = p;
        }
        fr.close();

        return start;
    }

    private static Person nameOnTop(Person start, String name) {
        Person p = start;
        Person prev = p;
        while (p.next != null) {
            if (p.name.equals(name)) {
                prev.next = p.next;
                p.next = start;
                start = p;
                System.out.println("New start is " + start.name + "\n");
                break;
            }
            prev = p;
            p = p.next;
        }

        return start;
    }

    public static void printNames(Person start) {
        Person p = start;

        while (p.next != null) {
            System.out.println(p.name);
            p = p.next;
        }
    }

    public static void quit(Person start) {
        Person p;

        while (start.next != null) {
            p = start;
            start = start.next;
            p.next = null;
        }
    }

    public static void main(String[] args) throws Exception {
        Person start = readFile();
        printNames(start);
        System.out.println("");
        start = nameOnTop(start, "Adolf");
        start = nameOnTop(start, "Sture");
        start = nameOnTop(start, "Kurt");
        printNames(start);
        quit(start);
    }

    private static class Person {
        private String name;
        private Person next;
    }
}


